<?php
/* 
 * Copyright (c) 2011 Antoine d'Otreppe de Bouvette
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Use this class as an entry point to run your application.
 * 
 * @author Antoine d'Otreppe <a.dotreppe@aspyct.org>
 */
final class Application {
    private $env;
    
    /**
     * @param Environment $env The environment to run with
     */
    public function __construct(Environment $env) {
        $this->env = $env;
    }
    
    /**
     * Run the website
     * 
     * @return void
     */
    public function run() {
        $initialBufferCount = ob_get_level();
        
        $request = $this->env->request;
        $handler = $this->env->dispatcher->findController($request);
        
        try {
            $response = $handler->handle($request);
            
            if (!($response instanceof Response)) {
                $message = "The controller '$handler' did not return a proper ".
                           "Response object.";
            	$this->env->logger->error($this, $message);
            	throw new HTTPInternalError(new RuntimeException($message));
            }
        }
        catch (HTTPFlowBreak $e) {
            $this->env->logger->warning($this,
                    "Controller <$handler> threw a " . get_class($e) .
                    " for {$request->getMethod()} {$request->getUri()}");
            $response = $e->buildResponse();
        }
        catch (Exception $e) {
            $this->env->logger->error($this, $e);
            $error = new HTTPInternalError($e);
            $response = $error->buildResponse();
        }
        
        // Kill the remaining output buffers
        while (ob_get_level() > $initialBufferCount) {
            ob_end_clean();
        }
        
        // "ob_gzhandler" is not always supported...
        //ob_start("ob_gzhandler");
        $response->output();
        //ob_end_flush();
    }
}
